<template>
  <div :class="{'mobile-create': showMobilePage}" class="project-order-create">
    <div class="box-shadow">
      <CreateOrder
        ref="orderInfoRef"
        :is-project-child="true"
        :no-display-props="['orderType']"
        :module-type="TAG_MODULES.PROJECT_CHANNEL"
        :category-required="false"
        style="margin-top:12px;"
        @orderSourceChange="orderSourceChange"
      />
      <CreateResource
        ref="resourceInfoRef"
        :no-display-props="['resourceType']"
        style="padding-top:10px;"
        @plateformChange="plateformChange"
        @orderFormChange="orderFormChange"
      />
      <CreatePublish
        ref="publishInfoRef"
        :order-id="id"
        :get-order-info="getOrderInfo"
        :is-link-required="isLinkRequired"
        :plateform-id="plateformId"
        :order-form="orderForm"
        style="margin-bottom: 36px;padding-top:10px;"/>
      <div class="box-block">
        <costBreakdownComponent
          ref="costBreakdownRef"
          :is-create="!isEdit"
          :order-info="detailInfo ? detailInfo.orderInfo : {}"
          :order-id="id"
          :is-detail="false"
          :is-project="true"
          :cost-belong-type="5"
        />
      </div>
    </div>
    <fixed-pagination>
      <div class="center">
        <el-button :loading="btnLoading" type="primary" size="small" @click="toSubmit">{{ isEdit ?'保存订单':'创建订单' }}</el-button>
        <el-button type="info" size="small" class="cancel-btn-style" @click="toBack">取消</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>
<script>
import CreateOrder from '@/components/CreateOrder/createOrderEx';
import CreateResource from '@/components/CreateOrder/createResource';
import CreatePublish from '@/components/CreateOrder/createPublish';
import costBreakdownComponent from '@/components/CreateOrder/costList';
import ElMessage from '@/utils/message';
import { getProjectOrder, projectChildEdit, projectChildAdd } from '@/api/project';
import { linkRequiredCheck } from '@/api/order';
import { hasRouteAuth } from '@/utils/permission';
import { TAG_MODULES } from '@/utils/const';
import mobileCreate from '@/mixins/mobileCreate';
export default {
  components: {
    CreateOrder,
    CreateResource,
    CreatePublish,
    costBreakdownComponent
  },
  mixins: [mobileCreate],
  data() {
    return {
      TAG_MODULES,
      id: '',
      btnLoading: false,
      detailInfo: {},
      isLinkRequired: false,
      plateformId: null,
      orderForm: ''
    };
  },
  computed: {
    isEdit() {
      return this.id !== '';
    }
  },
  created() {
    this.id = this.$route.params.id || '';
    if (this.id) {
      this.getOrderDetail();
    }
  },
  methods: {
    hasRouteAuth,
    getOrderDetail() {
      getProjectOrder(this.id).then(({ data }) => {
        this.detailInfo = data;
        if (data.orderInfo.orderPlatformId) {
          this.plateformId = data.orderInfo.orderPlatformId;
        }
        if (data.orderInfo.orderForm) {
          this.orderForm = data.orderInfo.orderForm;
        }
        // test
        this.detailInfo.orderInfo.priceTable = [{
          name: '含税',
          planPrice: data.orderInfo.planPrice === null ? '--' : (data.orderInfo.planPrice / 100).toFixed(2),
          channelPrice: data.orderInfo.channelPrice === null ? '--' : (data.orderInfo.channelPrice / 100).toFixed(2),
          totalPrice: data.orderInfo.taxAmount === null ? '--' : (data.orderInfo.taxAmount / 100).toFixed(2),
          disabled: false
        }, {
          name: '刊例',
          planPrice: data.orderInfo.articlesPlanPrice === null ? '--' : (data.orderInfo.articlesPlanPrice / 100).toFixed(2),
          channelPrice: data.orderInfo.articlesChannelPrice === null ? '--' : (data.orderInfo.articlesChannelPrice / 100).toFixed(2),
          totalPrice: data.orderInfo.articlesPrice === null ? '--' : (data.orderInfo.articlesPrice / 100).toFixed(2),
          disabled: false
        }, {
          name: '折扣',
          planPrice: data.orderInfo.planDiscountPrice === null ? '--' : data.orderInfo.planDiscountPrice,
          channelPrice: data.orderInfo.channelDiscountPrice === null ? '--' : data.orderInfo.channelDiscountPrice,
          totalPrice: data.orderInfo.discountPrice === null ? '--' : data.orderInfo.discountPrice,
          disabled: true
        }];
        if (this.$refs.orderInfoRef) {
          this.$refs.orderInfoRef.insertDetail(data);
          // this.$refs.orderInfoRef.$refs['formRef'].clearValidate('articlesPrice');
        }
        if (this.$refs.resourceInfoRef) this.$refs.resourceInfoRef.insertDetail(data);
        if (this.$refs.publishInfoRef) this.$refs.publishInfoRef.insertDetail(data);

        // if (this.$refs.discountInfoRef) this.$refs.discountInfoRef.insertDetail(data);
        if (this.$refs.costBreakdownRef) this.$refs.costBreakdownRef.insertDetail(data.costBreakdown);
        if (data.orderInfo.orderPlatformId && data.orderInfo.orderFormId) {
          this.handleCheckLinkrequired(data.orderInfo.orderFormId);
        }
      }).catch(err => {
        console.log(err);
      });
    },
    toSubmit(isValidate = true) {
      // 订单信息
      const orderInfoRefParams = this.$refs.orderInfoRef ? this.$refs.orderInfoRef.getParams().orderInfo : {};
      const marketParams = this.$refs.orderInfoRef ? this.$refs.orderInfoRef.getParams().clientInfo : {};
      // 资源信息
      const resourceInfoParams = this.$refs.resourceInfoRef ? this.$refs.resourceInfoRef.getParams() : {};
      // 发布信息
      const publishInfoParams = this.$refs.publishInfoRef ? this.$refs.publishInfoRef.getParams() : {};
      const orderParams = Object.assign(orderInfoRefParams, resourceInfoParams);

      // const discountInfoParams = this.$refs.discountInfoRef ? this.$refs.discountInfoRef.getParams() : {};
      // delete discountInfoParams.costConfirm;
      // 成本信息
      const discountInfoParams = this.$refs.costBreakdownRef ? this.$refs.costBreakdownRef.list : {};
      // discountInfoParams.costList.map(item => {
      //   item.taxCost = item.taxCost || item.taxCost === 0 ? (item.taxCost * 100).toFixed(0) : null;
      //   return item;
      // });
      const params = {
        orderInfo: orderParams,
        costBreakdown: discountInfoParams,
        clientInfo: marketParams,
        projectId: orderParams.projectId,
        publishInfo: publishInfoParams
      };
      const validatePromise = [];
      if (this.$refs.orderInfoRef) validatePromise.push(this.$refs.orderInfoRef.validateForm(isValidate));
      if (this.$refs.publishInfoRef) validatePromise.push(this.$refs.publishInfoRef.validateForm(isValidate));
      if (this.$refs.resourceInfoRef) validatePromise.push(this.$refs.resourceInfoRef.validateForm(isValidate));
      if (this.$refs.orderInfoRef.$refs['priceTableRef']) validatePromise.push(this.$refs.orderInfoRef.$refs['priceTableRef'].validate(isValidate));
      if (orderParams.orderKind) { // 传值判断订单分类超过五个不允许保存成功
        if (orderParams.orderKind.length > 5) {
          ElMessage.warning('订单分类不允许超过5个，请重新选择');
          return false;
        }
      }
      Promise.all(validatePromise).then(res => {
        if (params.orderInfo.operateModeParent && params.orderInfo.incomeTypeName) {
          if (params.orderInfo.operateModeParent === '飞博主体' && params.orderInfo.incomeTypeName === '媒介投放') {
            ElMessage.error('飞博主体收入类型不可选择媒介投放');
            return;
          }
          if (params.orderInfo.operateModeParent === '非飞博主体' && params.orderInfo.incomeTypeName === '媒体投放') {
            ElMessage.error('非飞博主体收入类型不可选择媒体投放');
            return;
          }
        }
        let discountError = true;
        if (this.$refs.discountInfoRef && !params.saveDraft) {
          discountError = this.$refs.discountInfoRef.validateEmpty(params.costBreakdown);
        }
        if (!discountError) {
          return;
        }
        if (this.isEdit) {
          this.editOrder(params);
        } else {
          this.addOrder(params);
        }
      }).catch((err) => {
        console.error(err);
        ElMessage.warning('请检查信息是否填写完整');
      });
    },
    addOrder(params) {
      this.btnLoading = true;
      projectChildAdd(params).then(res => {
        if (res.code === 200) {
          ElMessage.success('创建成功');
          this.$router.push({
            name: 'projectChild'
          });
        }
        this.btnLoading = false;
      }).catch(err => {
        console.error(err);
        this.btnLoading = false;
      });
    },
    editOrder(params) {
      this.btnLoading = true;
      projectChildEdit(this.id, params).then(res => {
        if (res.code === 200) {
          ElMessage.success('保存成功');
          this.$router.push({
            name: 'projectChildDetail',
            params: { id: this.id }
          });
        }
        this.btnLoading = false;
      }).catch(err => {
        console.error(err);
        this.btnLoading = false;
      });
    },
    toBack() {
      this.$router.push({
        name: 'projectChild'
      });
    },
    getOrderInfo() {
      const orderInfoRefParams = this.$refs.resourceInfoRef ? this.$refs.resourceInfoRef.getParams() : {};
      const platformOption = this.$refs.resourceInfoRef ? this.$refs.resourceInfoRef.orderPlatformOption : [];
      return {
        orderInfo: orderInfoRefParams,
        platformOption
      };
    },
    plateformChange(plateformId) {
      this.plateformId = plateformId;
    },
    orderSourceChange(val) {
      if (val === 2) {
        this.isLinkRequired = false;
      } else {
        const { orderFormId } = this.$refs.resourceInfoRef ? this.$refs.resourceInfoRef.getParams() : {};
        orderFormId && this.handleCheckLinkrequired(orderFormId);
      }
    },
    orderFormChange(orderForm) {
      this.orderForm = orderForm.value;
      this.handleCheckLinkrequired(orderForm.id);
    },
    handleCheckLinkrequired(orderFormId) {
      const params = {
        orderFormId,
        orderPlatformId: this.plateformId
      };
      const orderSource = this.$refs.orderInfoRef && this.$refs.orderInfoRef.paramsObj.orderSource;
      linkRequiredCheck(params).then(res => {
        if (res.code === 200) {
          this.isLinkRequired = orderSource === 2 ? false : res.data.isRequired;
        }
      }).catch(err => console.error(err));
    }
  }
};
</script>

<style lang="scss" scoped>
.project-order-create {
  margin: 16px;
  background-color: #fff;
  .box-shadow {
    padding-bottom: 40px;
  }
  & ::v-deep {
    .el-input__inner  {
      // width: 240px;
      line-height: 16px;
    }
    .el-date-editor.el-input {
      width: 240px;
    }
  }
}
.box-block {
  padding: 0px 24px 24px 24px;
  background-color: #fff;
}
</style>
